package com.ehotting.mqbd.core.service;

import com.ehotting.eaf.core.StringHelper;
import com.ehotting.mqbd.api.MQDBConstants;
import com.ehotting.mqbd.api.TaskStateActionConstants;
import com.ehotting.mqbd.api.bean.MQTaskData;
import com.ehotting.mqbd.api.bean.task.TaskStateRequest;
import com.ehotting.mqbd.api.enums.DirectionEnum;
import com.ehotting.mqbd.api.enums.TopicEnum;
import com.ehotting.mqbd.core.manager.AgentLinkManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TaskStateMQService {

    private Logger logger = LoggerFactory.getLogger(TaskStateMQService.class);

    @Autowired
    protected AgentLinkManager agentLinkManager;


    public void taskStart(MQService mqService,String agentId){
        this.sendTaskState(mqService,agentId, TaskStateActionConstants.TASK_START,"任务开始");
    }

    public void taskCancel(MQService mqService,String agentId){
        this.sendTaskState(mqService,agentId, TaskStateActionConstants.TASK_CANCEL,"任务中止");
    }

    public void taskFail(MQService mqService,String agentId){
        this.sendTaskState(mqService,agentId, TaskStateActionConstants.TASK_FAIL,"任务失败");
    }

    public void taskFinish(MQService mqService,String agentId){
        this.sendTaskState(mqService,agentId, TaskStateActionConstants.TASK_FINISH,"任务结束");
    }

    private void sendTaskState(MQService mqService,String agentId, String action, String msg){

        String clientIp = agentLinkManager.getClientIpByAgentId(agentId);

        logger.info("clientIp:{}.",clientIp);
        if(StringHelper.isBlank(clientIp)){
            logger.info("clientIp is null,getByMsgId by agentId[{}],return.",agentId);
            return;
        }

        String module = agentLinkManager.getModule(agentId);

        MQTaskData data = MQTaskData.create(TopicEnum.CONCURRENCY,
                clientIp,
                MQDBConstants.DISPATCHER_HOST,
                agentId,
                module,"");

        data.setDirection(DirectionEnum.RESPONSE.getCode());
        data.setResponse(createTaskState(action,msg,agentId));

        mqService.request(data);
    }

    public TaskStateRequest createTaskState(String action,String msg,String agentId){
        TaskStateRequest data = new TaskStateRequest();
        data.setUserId(agentLinkManager.getUserId(agentId));
        data.setMsg(msg);
        data.setId(String.valueOf(agentLinkManager.getProjectId(agentId)));
        data.setAction(action);
        return data;
    }


}
